package com.apes.enquiry.supplier.santouliubi.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.enquiry.supplier.santouliubi.SantouliubiApi;
import com.apes.enquiry.supplier.santouliubi.model.ShopManagement;
import com.apes.enquiry.supplier.santouliubi.repository.ShopManagementRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.masterdata.enumeration.model.BusinessParam;
import com.apes.scm.masterdata.enumeration.repository.BusinessParamRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 类描述：
 *
 * @ClassName ShopManagementService
 * @Description 描述
 * @Author wushilong
 * @Date 2022/12/13 19:13
 * @Version 1.0
 */
@Service("shopManagementService")
public class ShopManagementService extends DomainService {

    @Autowired
    private ShopManagementRepository shopManagementRepository;

    @Autowired
    private SantouliubiApi santouliubiApi;

    @Autowired
    private BusinessParamRepository businessParamRepository;

    /**
     * 发起门店注册申请/更新门店信息
     *
     * @param request
     * @return
     */
    public void save(SimpleRequest request) {
        JSONObject jo = request.getJO();
        //查询门店是否已注册
        ShopManagement shopManagement = null;
        String name = "";
        try {
            shopManagement = shopManagementRepository.findOne(JpaDsl.toCriteriaByEq("storeId", jo.getJSONObject("store").getString("id")
                    , "storeName", jo.getJSONObject("store").getString("name"))).get();
            if (!jo.getJSONObject("channel").getString("channelNumber").equals(shopManagement.getChannelNumber()) && !shopManagement.isState()){
                name = getName(shopManagement.getName());
            }
        } catch (Exception e) {
            shopManagement = new ShopManagement();
        }

        //保存门店信息在本地
        shopManagement.setStoreName(jo.getJSONObject("store").getString("name"));
        shopManagement.setStoreId(jo.getJSONObject("store").getString("id"));
        shopManagement.setAddress(jo.getString("address"));
        shopManagement.setContacts(jo.getString("contacts"));
        shopManagement.setContactPhone(jo.getString("contactPhone"));
        if (Objects.isNull(shopManagement.getId()))
            shopManagement.setCompany(jo.getJSONObject("store").getJSONObject("company").getString("id"));
        shopManagement.setCity(jo.getString("city"));
        shopManagement.setNote(jo.getString("note"));
        shopManagement.setApproval("待审核");
        shopManagement.setStatus("10");
        shopManagement.setChannelNumber(jo.getJSONObject("channel").getString("channelNumber"));
        shopManagement.setChannelName(jo.getJSONObject("channel").getString("channelName"));
        shopManagement = shopManagementRepository.saveAndFlush(shopManagement);

        if ("".equals(name)){
            name = shopManagement.getStoreName();
        }

        enroll(shopManagement, name);
    }

    /**
     * 门店注册
     *
     * @param shopManagement
     */
    private void enroll(ShopManagement shopManagement, String name) {
        //按三头六臂接口文档转换格式
        JSONObject body = new JSONObject();
        body.put("merchantsId", shopManagement.getChannelNumber());//渠道码
        body.put("merchantsRelatedNumber", shopManagement.getId());
        body.put("merchantsGarageId", shopManagement.getStoreId());
        body.put("name", name);
        body.put("provinceName", sub(shopManagement.getCity(), 1));
        body.put("cityName", sub(shopManagement.getCity(), 2));
        body.put("districtName", sub(shopManagement.getCity(), 3));
        body.put("address", shopManagement.getAddress());
        body.put("contactName", shopManagement.getContacts());
        body.put("contactMobi", shopManagement.getContactPhone());
        if (Objects.nonNull(shopManagement.getNote())) body.put("note", shopManagement.getNote());


        //调用三头六臂的接口注册门店
        JSONObject result = santouliubiApi.applyFor(body);
        if (Objects.nonNull(result.get("error"))) throw new RuntimeException(result.getJSONObject("error").getString("message"));
    }

    /**
     * 因为三头六臂同一个门店名称不能重复注册
     * @param name
     * @return 在三头注册的名称
     */
    private String getName(String name){
        Pattern pattern = Pattern.compile("[a-zA-Z]");
        Matcher matcher = pattern.matcher(name);
        if (matcher.find()) {
            int start = matcher.start();
            String letter = name.substring(start);
            int hashCode = letter.hashCode() + 1;
            char sort = (char) hashCode;
            String storeName = name.substring(0, start);
            return storeName + sort;
        }
        return name + "A";
    }


    /**
     * 截取省市区（以'/'分割）
     *
     * @param city    字符串
     * @param indexes 下标
     * @return
     */
    private String sub(String city, int indexes) {
        String ss = city;
        for (int i = 0; i < indexes; i++) {
            int subscript = ss.indexOf("/");
            if (subscript == -1) return ss;
            String substring = ss.substring(0, subscript);
            ss = ss.substring(subscript + 1);
            city = substring;
        }
        return city;
    }

    /**
     * 三头六臂审核通过回调接口
     *
     * @param json {"garageNumber":"修理厂编号","merchantsRelatedNumber":"渠道商申请相关单号"}
     * @return
     */
    public JSONObject informYes(JSONObject json) {
        JSONObject result = json.getJSONObject("data");
        ShopManagement shopManagement = shopManagementRepository.findOne(result.getString("merchantsRelatedNumber"));
        shopManagement.setApproval("审核通过");
        shopManagement.setStatus("40");
        shopManagement.setSantouId(result.getString("garageNumber"));
        shopManagement.setName(shopManagement.getStoreName());
        shopManagement.setState(true);
        shopManagement.setValid(true);
        shopManagementRepository.saveAndFlush(shopManagement);
        //返回三头六臂接收成功格式
        JSONObject enroll = new JSONObject();
        enroll.put("code", "1000");
        enroll.put("message", "");
        return enroll;
    }

    /**
     * 三头六臂审核不通过回调接口
     *
     * @param json {"reason":"原因","merchantsRelatedNumber":"渠道商申请相关单号"}
     * @return
     */
    public JSONObject informNo(JSONObject json) {
        JSONObject result = json.getJSONObject("data");
        ShopManagement shopManagement = shopManagementRepository.findOne(result.getString("merchantsRelatedNumber"));
        shopManagement.setApproval("审核不通过");
        shopManagement.setStatus("30");
        shopManagementRepository.saveAndFlush(shopManagement);
        //返回三头六臂接收成功格式
        JSONObject enroll = new JSONObject();
        enroll.put("code", "1000");
        enroll.put("message", "");
        return enroll;
    }

    /**
     * 刷新修理厂注册详情
     *
     * @param request
     * @return
     */
    public JSONObject flushShopManagement(SimpleRequest request) {
        String id = request.get("merchantsRelatedNumber");
        JSONObject store = request.get("store");
        ShopManagement shopManagement = shopManagementRepository.findByStoreIdAndSantouIdNotNull(store.getString("id"));
        if (Objects.isNull(shopManagement)) throw new RuntimeException("门店禁用！");
        return getJsonObject(id, store, shopManagement.getChannelNumber());
    }

    /**
     * 获取修理厂注册详情
     *
     * @param request
     * @return
     */
    public JSONObject getShopManagement(SimpleRequest request) {
        JSONObject node = (JSONObject) request.get("node");
        int index = node.getString("approval").indexOf("S");
        String id = node.getString("approval").substring(index);
        JSONObject store = node.getJSONObject("store");
        return getJsonObject(id, store, node.getJSONObject("channel").getString("id"));
    }

    /**
     * 调用三头六臂接口获取门店详情
     *
     * @param id
     * @param store
     * @return
     */
    private JSONObject getJsonObject(String id, JSONObject store, String merchantsId) {
        //调用三头六臂接口获取详情
        JSONObject body = new JSONObject();
        body.put("merchantsId", merchantsId);
        body.put("merchantsRelatedNumber", id);
        JSONObject shopInformation = santouliubiApi.getShopManagement(body);
        JSONObject result = shopInformation.getJSONObject("result");

        if (Objects.isNull(result)) throw new RuntimeException("获取三头六臂门店详情失败！");
        //修改本地门店数据
        ShopManagement shopManagement = shopManagementRepository.findOne(id);
        shopManagement.setApproval(result.getString("statusName"));
        shopManagement.setStatus(result.getString("status"));
        if ("40".equals(shopManagement.getStatus())) shopManagement.setValid(true);
        shopManagementRepository.saveAndFlush(shopManagement);

        //构造前端页面数据
        result.put("store", store);
        result.put("note", shopManagement.getNote());
        result.put("creator", shopManagement.getCreator());
        result.put("company", shopManagement.getCompany());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        result.put("createDate", sdf.format(shopManagement.getCreateDate()));
        return result;
    }


    /**
     * 调用三头六臂的接口，查询已经审核通过的门店列表
     *
     * @param request
     * @return
     */
    public void updateItem(SimpleRequest request) {

        BusinessParam businessParam = businessParamRepository.findOne("36");//三头渠道码
        JSONArray merchantsIds = JSONArray.parseArray(businessParam.getValue());
        merchantsIds.forEach(s -> {
            //调用三头六臂的接口，查询已经审核通过的门店
            JSONObject shopManagement = new JSONObject();
            shopManagement.put("merchantsId", s);
            shopManagement.put("garageNumber", "");
            shopManagement.put("name", "");
            JSONObject shopInformation = santouliubiApi.getShopInformation(shopManagement);
            JSONArray result = shopInformation.getJSONArray("result");//result:返回结果集
            if (Objects.isNull(result) || result.size() == 0) return;
            //查询本地门店数据
            List<ShopManagement> shopManagements = shopManagementRepository.findAll();
            Map<String, ShopManagement> collect = shopManagements.stream().filter(item -> StringUtils.isNotEmpty(item.getSantouId()))
                    .collect(Collectors.toMap(ShopManagement::getSantouId, item -> item));
            //同步三头门店数据到本地
            result.forEach(item -> {
                JSONObject json = (JSONObject) item;
                ShopManagement shopManagement1 = collect.get(json.getString("garageNumber"));
                if (Objects.isNull(shopManagement1)) return;
                shopManagement1.setSantouId(json.getString("garageNumber"));
                shopManagement1.setName(json.getString("name"));
                shopManagement1.setState("有效".equals(json.getString("statusName")));
                if (shopManagement1.isState()) {
                    shopManagement1.setApproval("审核通过");
                    shopManagement1.setStatus("40");
                }
            });
            shopManagementRepository.saveAll(shopManagements);
        });

    }

    /**
     * 门店启用/禁用
     *
     * @param request
     */
    public void enableDisable(SimpleRequest request) {
        JSONObject json = request.getJO();
        int index = json.getString("approval").indexOf("S");
        String id = json.getString("approval").substring(index);
        if (json.getBoolean("state")) {
            ShopManagement shopManagement = shopManagementRepository.findOne(id);
            if (!shopManagement.isValid()) throw new RuntimeException("门店尚未注册成功！无法启用/禁用");
            shopManagement.setState(true);
            //调用三头六臂接口启用
            JSONObject body = new JSONObject();
            body.put("merchantsId", json.getJSONObject("channel").getString("channelNumber"));
            JSONArray garageNumbers = new JSONArray();
            garageNumbers.add(shopManagement.getSantouId());
            body.put("garageNumbers", garageNumbers);
            santouliubiApi.enable(body);
        } else {
            ShopManagement shopManagement = shopManagementRepository.findOne(id);
            if (!shopManagement.isValid()) throw new RuntimeException("门店尚未注册成功！无法启用/禁用");
            shopManagement.setState(false);
            //调用三头六臂接口禁用
            JSONObject body = new JSONObject();
            body.put("merchantsId", json.getJSONObject("channel").getString("channelNumber"));
            JSONArray garageNumbers = new JSONArray();
            garageNumbers.add(shopManagement.getSantouId());
            body.put("garageNumbers", garageNumbers);
            santouliubiApi.disable(body);
        }
    }

    /**
     * 获取渠道码
     * @param deptId 门店ID
     * @return
     */
    public ShopManagement getOneShopManagement(String deptId){
        ShopManagement shopManagement = shopManagementRepository.findByStoreIdAndSantouIdNotNull(deptId);
        if (Objects.isNull(shopManagement) || !"40".equals(shopManagement.getStatus())) return null;
        return shopManagement;
    }

    public List findByStoreName(SimpleRequest request){
        String storeName = request.get("key");
        return shopManagementRepository.findByStoreName(storeName);
    }
}
